/**
 * Created by Administrator on 2017/3/30.
 */
app.controller('liveDetCtr',
    ['$scope','$location','$http','$rootScope','$routeParams','$sce', function ($scope,$location,$http,$rootScope,$routeParams,$sce) {

        //loading提示
        $("#globalLoading").css({
            top:'10rem',
            opacity:'1'
        });
        //获取详情信息
        $scope.sceControl = $sce.trustAsResourceUrl;
        var fileId=$routeParams.fileId;
        var articleId=fileId;
        console.log('articleId')
        console.log(articleId)
        var linkId=$routeParams.linkID;

        console.log("linkId")
        console.log(linkId)
        $scope.showLive=true;
        $scope.changshowLive=function () {
            $scope.showLive=true;
            $(".live_glasy").css("fontSize","18px");
            $(".live_chat").css("fontSize","15px");
            $(".live_glasy").css("color","#FC9105");
            $(".live_chat").css("color","#333333");
        };

        // 点击聊天室
        $scope.changshowChat=function () {
            $scope.showLive=false;
            $(".live_glasy").css("fontSize","15px");
            $(".live_chat").css("fontSize","18px");
            $(".live_glasy").css("color","#333333");
            $(".live_chat").css("color","#FC9105");

            //直播参与人点赞数
            $http.jsonp(liveCounts+'id=1696&source=1&jsoncallback=JSON_CALLBACK'
            ).success(function(data){
                console.log("新评论点赞数");
                console.log(data);
                $scope.liveCountClick=data.countClick

            }).error(function(data){

            });


            /**
             * 聊天室最新评论
             * */
            $scope.commeInputs=siteConfig.defaultHint;
            //直播详情，聊天室评论
            //id=3969
            /*var linkId=$routeParams.id;*/

            $http.jsonp(newComment+'id='+linkId+'&siteId=1&lastFileId=0&page=0&source='+liveSource+'&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                console.log("新评论");
                console.log(data);
                // 是否还有更多评论
                $scope.hasMorCom=data.hasMore;
                $scope.newCommenCon=data.list;
                console.log($scope.newCommenCon);
                $scope.newComCounts=data.totalCount;
                console.log($scope.newComCounts);
            }).error(function(data,header,config,status){
                console.log(data);
            });
        };


        //聊天室评论提交后刷新评论数据
        $scope.getNewCom=function(){
            $http.jsonp(newComment+'id='+linkId+'&siteId=1&lastFileId=0&page=0&source='+liveSource+'&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                console.log("新评论");
                console.log(data);
                // 是否还有更多评论
                $scope.hasMorCom=data.hasMore;
                $scope.newCommenCon=data.list;
                console.log($scope.newCommenCon);
                $scope.newComCounts=data.totalCount;
                console.log($scope.newComCounts);
            }).error(function(data,header,config,status){
                console.log(data);
            });
        };

        //获取全局配置信息
        $scope.getCommentInfo=function(){
            $http.jsonp(commInfo+'&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                console.log("全局评论信息");
                console.log(data);
                $scope.siteConfig=data.siteConfig.discuss;
                //评论框提示语
                siteConfig.defaultHint=$scope.siteConfig.defaultHint;
                //官方评论用户名
                siteConfig.defaultName=$scope.siteConfig.defaultName;
                $scope.defaultName=$scope.siteConfig.defaultName;
                //官方评论头像
                siteConfig.defaultIcon=$scope.siteConfig.defaultIcon;
                $scope.siteConfigDefaultIcon=$scope.siteConfig.defaultIcon;
                console.log("官方用户名");
                console.log($scope.defaultName);
                //是否关闭全站评论功能
                $scope.siteConfigAuditType=$scope.siteConfig.auditType;
                //全局评论颜色问题
                $scope.commStyleColor=$scope.siteConfig.styleColor;
                commentStyle=$scope.commStyleColor;
                $rootScope.changeComStyle();

                ////获取最新和热门评论
                //$scope.getNewCom();
                //$scope.getHotCom();

                //setTimeout(function () {

                //},1000)
            }).error(function(data,header,config,status){

            });

        };
        $scope.getCommentInfo();

        //点击评论数，跳转
        $scope.commentJump=function(){
            if($scope.newCommenCon.length>0){
                var scrollDistance=$("#newComCon").offset().top-60;
                $("body").animate({scrollTop:scrollDistance}, 300);
            }else{
                return
            }
        };

        //获取最新评论  page=0开始;加载更多评论
        var compage=0;
        //加载更多最新评论（只有最新评论有分页）id=3969全替换为articleId*****
        $scope.LoadMoreCom=function () {
            compage++;
            $http.jsonp(newComment+'id='+linkId+'&siteId=1&lastFileId=&page='+compage+'&source='+liveSource+'&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                // 是否还有更多评论
                $scope.hasMorCom=data.hasMore;
                $scope.newCommenCon=$scope.newCommenCon.concat(data.list);
            }).error(function(data,header,config,status){

            });

        };



        /**
         * 详情信息
         * */

            var publicArr=[];
            var json = {};
            //id=74 直播详情数据id=上级的linkId
            //原请求地址 liveDetailData+'index=0&id='+linkId+'&start=0&count=20&lastFileId=0&la=40.047023&lo=116.313423&jsoncallback=JSON_CALLBACK'
            $http.jsonp(liveDetailData+'sindex=0&id='+linkId+'&lastFileId=0&page=0&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                $scope.liveDetail=data;
                $scope.liveDetailArray=data.list;

                //loading提示
                $("#globalLoading").animate({
                    top:'20px',
                    opacity:'0'
                },500);

                if($scope.liveDetailArray.length!=0){
                    $scope.lastFileId=$scope.liveDetailArray[$scope.liveDetailArray.length-1].fileId;
                }
                    $scope.liveDataiPage=0;
                //所有直播流对象，判断如果vedio中没有对象就是图文直播
                $scope.liveImgOrVedioObj=data.main.config.videos;
                if($scope.liveDetail.main.config.videos.length>0){
                    console.log("直播url")
                    console.log($scope.liveImgOrVedioObj[0].webLiveUrl)
                    // liveAllUrl=$scope.liveDetail.main.config.videos;
                    window.liveAllUrl.push({"webLiveUrl":$scope.liveImgOrVedioObj[0].webLiveUrl,"streamID":$scope.liveImgOrVedioObj[0].streamID,"webPlaybackUrl":$scope.liveImgOrVedioObj[0].webPlaybackUrl});
                    console.log("直播流ssssurl");
                    console.log(liveAllUrl[0].webLiveUrl);
                }
                console.log("详情")
                console.log($scope.liveDetail)
                //是否关闭该篇稿件评论功能
                $scope.currentDiscussClosed=data.main.discussClosed;

                if(data.list.length>=20){
                   $scope.loadDetailMoreButtonOne=true;
                }else{
                   $scope.noDetailLoadMoreButton=true;
                }
                for(var i=0;i<data.list.length;i++){
                    var value=data.list[i].publishtime;
                    // console.log("时间数组")
                    // console.log(value)
                    var indexSpac=value.indexOf(" ");
                    var lastHourString=value.substring(0,indexSpac);
                    if(!json[lastHourString]){
                        publicArr.push(lastHourString);
                        json[lastHourString] = 1;
                    }
                }
                console.log("时间数组")
                console.log(publicArr);
                $scope.publicArr=publicArr;

                //直播状态
                $scope.liveDetailStatus=$scope.liveDetail.main.status;
                //直播预告开始时间
                $scope.liveDetailStartTime=$scope.liveDetail.main.startTime;

                if(data.main.status==1){
                    //直播流状态
                    var stream=liveAllUrl[0].streamID;
                    console.log("stream")
                    console.log(stream)
                    $scope.streamCurrentStatus=data.currentStatus[stream];
                    //alert($scope.streamCurrentStatus);

                }else if(data.main.status==2){
                    //有无精彩回放
                    var webPlaybackUrl=data.main.config.videos[0].webPlaybackUrl;
                    console.log("直播回放流")
                    console.log(webPlaybackUrl)
                    $scope.webPlaybackUrl=data.main.config.videos[0].webPlaybackUrl;
                    window.liveAllUrl=[];
                    window.liveAllUrl.push({"webLiveUrl":webPlaybackUrl,"streamID":'',"webPlaybackUrl":''});
                }





                //var webPlaybackUrl=liveAllUrl[0].webPlaybackUrl;
                //console.log("当前回放流")
                //console.log(webPlaybackUrl)
                //$scope.streamCurrentStatus=webPlaybackUrl;
                //if($scope.liveDetailStatus==2&&$scope.streamCurrentStatus){
                //    window.liveAllUrl.push({"webLiveUrl":webPlaybackUrl});
                //}

               //是否有直播
                if($scope.liveImgOrVedioObj.length>0){
                    var option = {
                        "live_url":liveAllUrl[0],
                        "width" : 480,
                        "height" : 320
                        //...可选填其他属性
                    };

                    var player = new qcVideo.Player("id_video_container", option);

                }



            }).error(function(data,header,config,status){
            });

        //直播线路切换问题
        $scope.chanLivePath=function(arg){
            //window.liveAllUrl[0]=$scope.liveImgOrVedioObj[arg].webLiveUrl;
            window.liveAllUrl[0]={"webLiveUrl":$scope.liveImgOrVedioObj[arg].webLiveUrl,"streamID":$scope.liveImgOrVedioObj[arg].streamID,"webPlaybackUrl":$scope.liveImgOrVedioObj[arg].webPlaybackUrl};
            console.log(window.liveAllUrl[0].webLiveUrl);
            $('.liveChannelPath').each(function(index,val){
                $(val).css({'border':'1px solid #fff','color':'#fff'})
            });
            var currentLivePath=$('.liveChannelPath')[arg];
            $(currentLivePath).css({'border':'1px solid #fc9105','color':'#fc9105'})
        };
        // })

        /**
         * 详情加载更多
         * */
        $scope.loadMorLiveDetail=function () {
            $scope.liveDataiPage++;
            $http.jsonp(liveDetailData+'sindex=0&id='+linkId+'&lastFileId='+$scope.lastFileId+'&page='+$scope.liveDataiPage+'&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                $scope.liveDetail=data;
                $scope.liveDetailArray=$scope.liveDetailArray.concat(data.list);
                console.log("加载更多数据")
                console.log($scope.liveDetailArray)
                //所有直播流对象，判断如果vedio中没有对象就是图文直播
                // $scope.liveImgOrVedioObj=data.main.config.videos;
                // if($scope.liveDetail.main.config.videos.length>0){
                //     console.log("加载更多直播url")
                //     console.log($scope.liveImgOrVedioObj[0].webLiveUrl)
                // }
                console.log("详情加载更多")
                console.log($scope.liveDetail)
                if(data.list.length>=20){
                    $scope.loadDetailMoreButtonOne=true;
                }else{
                    $scope.loadDetailMoreButtonOne=false;
                    $scope.noDetailLoadMoreButton=true;
                }
                for(var i=0;i<data.list.length;i++){
                    var value=data.list[i].publishtime;
                    // console.log("时间数组")
                    // console.log(value)
                    var indexSpac=value.indexOf(" ");
                    var lastHourString=value.substring(0,indexSpac);
                    if(!json[lastHourString]){
                        publicArr.push(lastHourString);
                        json[lastHourString] = 1;
                    }
                }
                console.log("加载更多时间数组")
                console.log(publicArr);
                $scope.publicArr=publicArr;
            }).error(function(data,header,config,status){
            });
        }




        //直播详情语音播放当前audio
        $scope.playAudio=function ($event) {
            console.log("当前audio");
            console.log(angular.element($event.target).next());
            var audio=angular.element($event.target).next();
            audio[0].play();
            //时长
            console.log(Math.round(audio[0].duration))
        };
        /*var timeFormat = function(seconds){
         var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
         var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
         return m+":"+s;
         };*/
        //直播详情视频播放当前vedio
        $scope.playVedio=function ($event) {
            console.log("当前vedio");
            var currentVedio=angular.element($event.target).parent().parent().find('video');
            console.log(angular.element($event.target).parent().parent().find('video'));
            currentVedio[0].play();
            var control=angular.element($event.target).parent().parent().find('.control');
            console.log("control")
            $(control).css("bottom","0");
            var duration=angular.element($event.target).parent().parent().find('.duration');
            console.log("duration");
            duration[0].innerText=Math.round(currentVedio[0].duration);
            console.log(currentVedio[0].duration);
            angular.element($event.target).css("display","none");
            var btnPlay=angular.element($event.target).parent().parent().find('.btnPlay')
            $(btnPlay).addClass('paused');
            currentVedio.on('timeupdate', function() {
                var currentPos =Math.round(currentVedio[0].currentTime) ;
                var maxduration = currentVedio[0].duration;
                var perc = 100 * currentPos / maxduration;
                var timeBar=angular.element($event.target).parent().parent().find('.timeBar');
                var current=angular.element($event.target).parent().parent().find('.current');
                var timeBall=angular.element($event.target).parent().parent().find('#timeBall');

                $(timeBar).css('width',perc+'%');
                $(timeBall).css('left',perc+'%');
                $(current).text(currentPos);
            })

        };
        //全屏
        $scope.btnFS=function ($event) {
            console.log("当前vedio");
            var currentVedio=angular.element($event.target).parent().parent().parent().find('video')
            console.log(currentVedio);
            if($.isFunction(currentVedio[0].webkitEnterFullscreen)) {
                currentVedio[0].webkitEnterFullscreen();
            }
            else if ($.isFunction(currentVedio[0].mozRequestFullScreen)) {
                currentVedio[0].mozRequestFullScreen();
            }
            else {
                console.log('Your browsers doesn\'t support fullscreen');
            }

        };
        //点击播放三角
        $scope.btnPlay=function ($event) {
            var currentVedio=angular.element($event.target).parent().parent().parent().find('video');
            console.log("当前vedio");
            console.log(currentVedio);
            if(currentVedio[0].paused || currentVedio[0].ended) {
                angular.element($event.target).addClass('paused');
                currentVedio[0].play();
            }
            else {
                angular.element($event.target).removeClass('paused');
                currentVedio[0].pause();
            }
        };


        /**评论提交
         * */
            //弹出模态框
        $scope.showModeAndRepley=function ($event) {
            //if($rootScope.uid_fouNder){
            $('#commentModle').css('display',"block");
            $("#commentArea").css('display',"block");
            $("#comInput").focus();
            $("#comInput").attr("placeholder","请输入内容:");
            $("#comm_text_footer").css('display',"none");
            //}else{
            //    window.location='http://172.19.32.122:9081/SSOv2/user/login_app';
            //}
            $scope.parentId=0;
        };
        //取消模态框
        $scope.cancelCom=function () {
            //添加input图片上传的的占位
            $("#uploadImagForm").css({display:'block'});
            //清除选中图片
            $(".imgCont").children().remove();
            //清除上传图片的对象
            window.uploadFile="";
            $("#comInput").val("");
            $('#commentModle').css('display',"none");
            $("#commentArea").css('display',"none");
            $("#comm_text_footer").css('display',"block");
        };

        //回复评论
        $scope.replayCom=function (userID,userName) {
            $('#commentModle').css('display',"block");
            $("#commentArea").css('display',"block");
            $("#comm_text_footer").css('display',"none");
            // 提交评论使用
            $scope.parentId=parentId;
            $scope.userName=userName;
            $scope.ParentUserID=ParentUserID;
            $("#comInput").attr("placeholder","@"+userName+":");
        };

        // 发送评论
        // 发送评论
        $scope.sendCom=function () {
            var topicTitle= $scope.liveDetail.main.title;
            console.log("文字的标题")
            console.log(topicTitle)
            if(!window.uploadFile){
                //只提交文字评论
                var sendMesg=$("#comInput").val();
                console.log("评论信息");
                console.log(sendMesg);
                var logUserId=uid_fouNder;
                var LogUserName=username_fouNder;
                //匿名评论
                if(!uid_fouNder){
                    logUserId=0;
                    LogUserName="触屏用户";
                }

                var siteID = 1, rootID = articleId, parentID = $scope.parentId, parentUser = $scope.userName,
                    parentUserID = $scope.ParentUserID, topic =topicTitle, userID=logUserId
                    , userName=LogUserName, type = 0,content=sendMesg;

                //提交回复
                $.ajax({
                    type: "post",
                    url: sentComent,
                    data:{
                        "siteID": siteID,
                        "rootID": articleId,
                        "parentID": parentID,
                        "parentUser": parentUser,
                        "parentUserID": parentUserID,
                        "topic": topic,
                        "userID": userID,
                        "userName": userName,
                        "type": type,
                        "content":content,
                        "channel":1,
                        "sourceType":liveSource

                    },
                    dataType : "json",
                    //jsonp: "jsoncallback",
                    //jsoncallback:"jsoncallback",
                    success: function(data){
                            console.log(data);
                            alert("评论成功！");
                            $scope.getNewCom();
                            console.log("发送内容为：");
                            console.log(sendMesg);
                            $("#comInput").val("");
                            $('#commentModle').css('display',"none");
                            $("#commentArea").css('display',"none");
                            $("#comm_text_footer").css('display',"block");
                            $('.up-section').each(function(el,value){
                                console.log("图片数组")
                                alert()
                                console.log(el)
                                console.log(value)
                                //arrFiles=[]
                                //imgArr=[]
                                loadImg();
                            });

                    },
                    error: function(){
                        alert("评论失败！2");
                        $('#commentModle').css('display',"none");
                        $("#commentArea").css('display',"none");
                        $("#comm_text_footer").css('display',"block");
                    }
                });
            }else{
                //即提交评论文字，又上传图片

                var imgUrl=window.uploadFile;
                console.log("提交的图片信息")
                console.log(imgUrl)

                //图片提交
                var formdata = new FormData();
                formdata.append("Filedata", imgUrl);
                formdata.append("siteID", 1);
                formdata.append("location", 0);
                formdata.append("userId", "0");
                formdata.append("fileType", "picture");
                formdata.append("uniqid", "B715C9A0-D580-46F2-ABD1-F244EA24C934");

                $.ajax({
                    type:'POST',
                    url: commUpload,
                    processData: false,
                    data: formdata,
                    async:false,
                    contentType: false,    //这个一定要写
                    dataType:'json',
                    success: function(result){
                        //成功后处理代码
                        //self.onSuccess(file, result);
                        //if(self.curUploadFile.length==0){
                        // 回调全部完成方法
                        //self.onComplete("全部完成");
                        console.log("上传成功");
                        console.log(result)
                        console.log("上传成功url");
                        var comimgUrl=JSON.parse(result).fileList[0].url;
                        console.log("comimgUrl")
                        console.log(comimgUrl);


                        setTimeout(function(){
                            var sendMesg=$("#comInput").val();
                            console.log("评论信息");
                            console.log(sendMesg);
                            var logUserId=uid_fouNder;
                            var LogUserName=username_fouNder;
                            //匿名评论
                            if(!uid_fouNder){
                                logUserId=0;
                                LogUserName="触屏用户";
                            }
                            var siteID = 1, rootID = articleId, parentID = $scope.parentId, parentUser = $scope.userName,
                                parentUserID = $scope.ParentUserID, topic =topicTitle, userID=logUserId
                                , userName=LogUserName, type = 0,content=sendMesg;

                            //提交回复
                            $.ajax({
                                type: "post",
                                url: sentComent,
                                data:{
                                    "siteID": siteID,
                                    "rootID": articleId,
                                    "parentID": parentID,
                                    "parentUser": parentUser,
                                    "parentUserID": parentUserID,
                                    "topic": topic,
                                    "userID": userID,
                                    "userName": userName,
                                    "type": type,
                                    "content":content,
                                    "channel":1,
                                    "sourceType":liveSource,
                                    "imgUrl":comimgUrl

                                },
                                dataType : "json",
                                //jsonp: "jsoncallback",
                                //jsoncallback:"jsoncallback",
                                success: function(data){
                                    console.log(data);
                                    alert("图片上传成功！");
                                    $scope.getNewCom();
                                    console.log("发送内容为：");
                                    console.log(sendMesg);
                                    //清空全局需要上传的图片对象
                                    window.uploadFile=""
                                    //添加input图片上传的的占位
                                    $("#uploadImagForm").css({display:'block'});
                                    //清除选中图片
                                    $(".imgCont").children().remove();
                                    $("#comInput").val("");
                                    $('#commentModle').css('display',"none");
                                    $("#commentArea").css('display',"none");
                                    $("#comm_text_footer").css('display',"block");
                                    $('.up-section').each(function(el,value){
                                        console.log("图片数组")
                                        alert()
                                        console.log(el)
                                        console.log(value)
                                        //arrFiles=[]
                                        //imgArr=[]
                                        loadImg();
                                    });


                                },
                                error: function(){
                                    alert("图片上传失败");
                                    //清空全局需要上传的图片对象
                                    window.uploadFile=""
                                    //添加input图片上传的的占位
                                    $("#uploadImagForm").css({display:'block'});
                                    //清除选中图片
                                    $(".imgCont").children().remove();
                                    $('#commentModle').css('display',"none");
                                    $("#commentArea").css('display',"none");
                                    $("#comm_text_footer").css('display',"block");
                                }
                            });
                        },1000)
                    },
                    error: function(){
                        self.onFailure(file);
                    }

                });

            }
        };

        $scope.lunchaMorChilCom=true;
        //获取子评论加载更多更多内容 id为每条父评论的id号
        $scope.checkMorChildCom=function (id,index) {
            $scope.lunchaMorChilCom=false;

            $http.jsonp(replayComent+'id='+id+'&page=0&siteId=1&source=1&jsoncallback=JSON_CALLBACK'
            ).success(function(data,header,config,status){
                //点击查看更多子评论之前
                $scope.beforLoadMorChid=$scope.newCommenCon[index].topDiscuss.list;
                //点击查看更多子评论之后
                $scope.newCommenCon[index].topDiscuss.list=data.list;

                // 是否还有更多评论
                /*console.log("是否有更多")
                 console.log(data.hasMore)*/
                $scope.hasNoChildMorCom={};
                $scope.hasChildMorCom={};
                if(data.hasMore){
                    $scope.hasChildMorCom.index=true;
                }else{
                    $scope.hasNoChildMorCom.index=true;

                }
                //获取评论
                // $scope.commenCon=data.list;
            }).error(function(data,header,config,status){
            });
        };


        //回到顶部
        $(".fiBtn").hide();
        $(window).on("scroll", function(){
            if($(window).scrollTop() >0){
                $(".fiBtn").show();
            }else{
                $(".fiBtn").hide();
            }
        });
        $scope.goBackTop=function () {
            $("body").animate({scrollTop: 0}, 300);
        };
    }]);
